//
//  ControlTemplateViewPhotoController.m
//  Uhomebk
//
//  Created by 揭婧雯 on 17/3/3.
//  Copyright © 2017年 com.segi. All rights reserved.
//

#import "ControlTemplateViewPhotoController.h"
#import "SEGShowPhotoView.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

#if __has_include(<commonThirds/SEGImagePickerManager.h>)
#import <commonThirds/SEGImagePickerManager.h>
#else
#import "SEGImagePickerManager.h"
#endif

#pragma mark -
#pragma mark 图像框控件【photo】

#import <CoreLocation/CoreLocation.h>
#define PICWIDTH 63

@interface ControlTemplateViewPhotoController () <UIScrollViewDelegate,SEGShowPhotoViewDelegate,SEGImagePickerManagerDelegate> {
    CustomButtonView* uploadPhotoBtn;
    UIImagePickerController *pickerController;
    UIImageView* showImageView;//显示一张图片
    UIImageView* cornerImageView;
    UILabel *cornerLabel;//显示图片数量
}
@property (nonatomic, strong) NSString* defaultValue;
@property (nonatomic, strong) SEGImagePickerManager *imagePicker;

@end

@implementation ControlTemplateViewPhotoController

static ControlTemplateViewPhotoController* sharedManagerPhotoInter = nil;

+ (ControlTemplateViewPhotoController*)sharedManagerPhoto
{
    sharedManagerPhotoInter = [[self alloc] init];
    
    return sharedManagerPhotoInter;
}

/**
 *  图片变量初始化
 */
- (void)initVar
{
    isUploadSuccess = NO;
    _valueStr = @"";
    _param_id = [SEGUtils ValueToString:[_params valueForKey:@"attrInstId"]];
    _optional = [SEGUtils ValueToString:[_params valueForKey:@"required"]];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initVar];
    
    queue = [[NSOperationQueue alloc] init];
    [queue setMaxConcurrentOperationCount:1];
    
    _picDataArray = [[NSMutableArray alloc] init];
    saveImageArray = [[NSMutableArray alloc] init];
    
    _bgMainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 100)];
    _bgMainView.backgroundColor = kColor_W;
    self.tempBgView = _bgMainView;
    [self.view addSubview:_bgMainView];
    
    UILabel* titleLabel = [[UILabel alloc] init];
    [titleLabel extendAttributedString:[_params valueForKey:@"title"] lineSpace:LINESPACE_6 font:kFont_16];
    [titleLabel setFont:kFont_16];
    [titleLabel setTextColor:kColor_1];
    titleLabel.numberOfLines = 0;
    titleLabel.lineBreakMode = NSLineBreakByCharWrapping;
    [_bgMainView addSubview:titleLabel];
    [titleLabel sizeToFit];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(HEADSPACE);
        make.top.mas_equalTo(HEADSPACE);
        make.width.mas_equalTo(TITLE_WIDTH);
    }];
    
    contentView = [[UIView alloc] initWithFrame:CGRectMake(CONTENTMARGIN_LEFT, 0, CGRectGetWidth(_bgMainView.bounds) - CONTENTMARGIN_LEFT, CGRectGetHeight(_bgMainView.bounds))];
    [_bgMainView addSubview:contentView];
    
    ////////判断defaultValue是否有值
    if ([[_params valueForKey:@"attrValue"] length] > 0) {
        _defaultValue = [_params valueForKey:@"attrValue"];
    }
    
    ////////是否可读 0-不显示 1-显示
    if ([[SEGUtils ValueToString:[_params valueForKey:@"readable"]] isEqualToString:@"0"]) {
        _bgMainView.frame = CGRectMake(0, 0, CGRectGetWidth(_bgMainView.bounds), 0);
    }
    
    //线条
    UIView* lineView = [[UIView alloc] initWithFrame:CGRectMake(LINEMARGIN_LEFT, CGRectGetHeight(_bgMainView.bounds) - 0.5, CGRectGetWidth(_bgMainView.bounds), 0.5)];
    lineView.backgroundColor = kColor_L2;
    lineView.tag = 8888;
    [_bgMainView addSubview:lineView];
    
    ////////是否必填 //是否可读 1-必须 0-可不填
    _optional = [SEGUtils ValueToString:[_params valueForKey:@"required"]];
    
    ////////是否可写 //是否可读 0-不可写 1-可写
    if ([[SEGUtils ValueToString:[_params valueForKey:@"writable"]] isEqualToString:@"0"]) {
        //不可写 attrValue没有值
        NSString *attrValue = [_params valueForKey:@"attrValue"];
        NSArray *arr = [SEGUtils arrayWithJsonString:attrValue];
        if (arr.count != 0) {
            titleLabel.frame = CGRectMake(HEADSPACE, 0, 102, 50);
            lineView.frame = CGRectMake(LINEMARGIN_LEFT, CGRectGetHeight(_bgMainView.bounds) - 0.5, CGRectGetWidth(_bgMainView.bounds), 0.5);
            UILabel* alabel = [[UILabel alloc] initWithFrame:CGRectMake(CONTENTMARGIN_LEFT, 0, CGRectGetWidth(_bgMainView.bounds) - 122, CGRectGetHeight(_bgMainView.bounds))];
            [alabel setFont:kFont_16];
            [alabel setTextColor:kColor_1];
            [_bgMainView addSubview:alabel];
        }
        else{
            _bgMainView.frame = CGRectMake(0, 0, CGRectGetWidth(_bgMainView.bounds), 0);
        }
    }
    else {
        //上传图片按钮
        UIImage* image = [UIImage imageWithContentsOfFile:SEGPicName(@"btn_addpic")];
        uploadPhotoBtn = [[CustomButtonView alloc] init];
        uploadPhotoBtn.frame = CGRectMake(0, (CGRectGetHeight(contentView.bounds) - image.size.height) / 2, image.size.width, image.size.height);
        [uploadPhotoBtn addTarget:self action:@selector(onBtnUpAction:) forControlEvents:UIControlEventTouchUpInside];
        [uploadPhotoBtn setImage:image forState:UIControlStateNormal];
        [contentView addSubview:uploadPhotoBtn];
    }
    
    lineView.frame = CGRectMake(lineView.frame.origin.x, CGRectGetHeight(_bgMainView.bounds) - 0.5, CGRectGetWidth(lineView.bounds), 0.5);
    
    [self paddingDefaultValue];
    
}


/**
 *  选择图片提示框
 */
- (void)onBtnUpAction:(CustomButtonView*)sender
{
    //判断上传图片最大数
    NSInteger photoMax = [SEGUtils ValueToInteger:[_params valueForKey:@"contentLengthLimit"]];
    if (_picDataArray.count  >= photoMax) {
        [SEGAlertView showTmepMessageWithMessage:[NSString stringWithFormat:@"图片最多可上传%@张", [_params valueForKey:@"contentLengthLimit"]]];
        return;
    }
    if ([_params[@"widgetType"] isEqualToString:@"camera"]) {
        [self openCamera];
        return;
    }
    if ([_params[@"widgetType"] isEqualToString:@"album"]) {
        [self openAlbumWithMaxNum:photoMax];
        return;
    }

    UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:@"选择图片" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    
    //打开相机
    UIAlertAction* camAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction* _Nonnull action) {
        [self openCamera];
    }];
    
    //打开相册
    UIAlertAction* photoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction* _Nonnull action) {
        
        [self openAlbumWithMaxNum:photoMax];
    }];
    
    //取消
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertVC addAction:camAction];
    [alertVC addAction:photoAction];
    [alertVC addAction:cancelAction];
    // 25784 【深到家v1.1.0】IOS 工单无法选择服务分类
    UIViewController *currentVC = [[SEGUhomeMediator sharedInstance] seg_getCurrentController:nil];
    [currentVC presentViewController:alertVC animated:YES completion:nil];
}


/**
 打开相机
 */
- (void)openCamera {
    self.imagePicker = [[SEGImagePickerManager alloc] init];
    self.imagePicker.delegate = self;
    self.imagePicker.sourceType = SEGImagePickerManagerSourceTypeCamera;
    self.imagePicker.allowsEditing = NO;
    
    // 这里坑死了，用当前vc present相机相册，由于视图层级嵌套的原因，会导致相册控件跳动
    [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil superVC:self.masterVC.navigationController];
}


/**
 打开相册
 @param photoMax 最大选择数目
 */
-(void)openAlbumWithMaxNum:(NSInteger)photoMax {
    self.imagePicker = [[SEGImagePickerManager alloc] init];
    self.imagePicker.delegate = self;
    self.imagePicker.sourceType = SEGImagePickerManagerSourceTypePhotoLibrary;
    self.imagePicker.allowsEditing = NO;
    self.imagePicker.maxImagesCount = photoMax - _picDataArray.count;
    
    // 这里坑死了，用当前vc present相机相册，由于视图层级嵌套的原因，会导致相册控件跳动
    [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil superVC:self.masterVC.navigationController];
}

/**
 *  所有图片全部重置位置
 */
- (void)onResetImageArea
{
    //判断是iphone6plus以下
    CGSize size = [[UIScreen mainScreen] bounds].size;
    int showPicNum = 2;
    if (size.height < 667) {
        showPicNum = 2;
    }
    else {
        showPicNum = 3;
    }
    
    int linex = 0;
    int liney = 10;
    for (int i = 0; i < [contentView.subviews count]; i++) {
        UIImageView* aImageView = [contentView.subviews objectAtIndex:i];
        if ([aImageView isKindOfClass:[UIImageView class]]) {
            aImageView.frame = CGRectMake(linex * (PICWIDTH+10), liney, PICWIDTH, PICWIDTH);
            linex++;
            if (linex > showPicNum - 1) {
                linex = 0;
                liney += (PICWIDTH+10);
            }
        }
    }
    
    //移动按钮位置
    for (CustomButtonView* abtn in contentView.subviews) {
        if ([abtn isKindOfClass:[CustomButtonView class]]) {
            int picCount = (int)[contentView.subviews count];
            
            int lineCount = (picCount / (showPicNum + 0.0) > picCount / showPicNum) ? (picCount / showPicNum) + 1 : picCount / showPicNum;
            
            if ((picCount - 1) % showPicNum == 0) {
                abtn.frame = CGRectMake(0, liney, PICWIDTH, PICWIDTH);
                
                contentView.frame = CGRectMake(CONTENTMARGIN_LEFT, 0, CGRectGetWidth(contentView.bounds), PICWIDTH+20 + (lineCount - 1) * (PICWIDTH+20));
                _bgMainView.frame = CGRectMake(0, 0, CGRectGetWidth(_bgMainView.bounds), CGRectGetHeight(contentView.bounds));
                UIView* lineView = [_bgMainView.subviews objectAtIndex:2];
                lineView.frame = CGRectMake(lineView.frame.origin.x, CGRectGetHeight(_bgMainView.bounds) - 0.5, CGRectGetWidth(lineView.bounds), CGRectGetHeight(lineView.bounds));
            }
            else {
                abtn.frame = CGRectMake(linex * (PICWIDTH+10), liney, PICWIDTH, PICWIDTH);
                contentView.frame = CGRectMake(CONTENTMARGIN_LEFT, 0, CGRectGetWidth(contentView.bounds), PICWIDTH+20 + (lineCount - 1) * (PICWIDTH+20));
                _bgMainView.frame = CGRectMake(0, 0, CGRectGetWidth(_bgMainView.bounds), CGRectGetHeight(contentView.bounds));
                UIView* lineView = [_bgMainView.subviews objectAtIndex:2];
                lineView.frame = CGRectMake(lineView.frame.origin.x, CGRectGetHeight(_bgMainView.bounds) - 0.5, CGRectGetWidth(lineView.bounds), CGRectGetHeight(lineView.bounds));
            }
            [self.fundelegate onFeeRefeshUI];
        }
    }
    
    if ([contentView.subviews count] == 1)
    {
        _optional = [SEGUtils ValueToString:[_params valueForKey:@"required"]];
    }
    else {
        _optional = @"0";
    }
}

#pragma mark - <SEGImagePickerManagerDelegate> methods

- (void)seg_imagePickerManager:(SEGImagePickerManager *)manager didFinishPickingPhotos:(NSArray<UIImage *> *)photos assets:(NSArray<PHAsset *> *)assets isSelectOriginalPhoto:(BOOL)isSelect {
    
    WeakSelf;
    [photos enumerateObjectsUsingBlock:^(UIImage * _Nonnull subImage, NSUInteger idx, BOOL * _Nonnull stop) {
        PHAsset *subAssets = assets[idx];
        
        // 保存图片到document目录下
        NSData *data = [UIImage zipImageWithImage:[SEGUtils fixOrientation:subImage] withCompressionQuality:0.5];
        NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateStyle:NSDateFormatterShortStyle];
        [dateFormatter setDateFormat:@"MMddHHmmssSSSS"];
        NSString* createTime = [dateFormatter stringFromDate:subAssets.creationDate];
        
        NSString* fileName = [NSString stringWithFormat:@"%@/%@.jpg", filePath, createTime];

        //根据照片拍摄时间  -- 压缩图片+加载水印
        if ([[SEGUtils ScaleImageAndMakeLogo:[UIImage imageWithData:data] creatDate:subAssets.creationDate] writeToFile:fileName atomically:YES]) {
            if (fileName) {
                [weakSelf.picDataArray addObject:fileName];
            }
            weakSelf.optional = @"0";
        }
        weakSelf.valueStr = [weakSelf.picDataArray yy_modelToJSONString];
    }];
    
    [self addImageView:[UIImage imageWithContentsOfFile:[_picDataArray objectAtIndex:0]]];
    [self onResetImageArea];
}

- (void)seg_imagePickerManagerDidCancel:(SEGImagePickerManager *)picker {
    
}

#pragma mark - ================<删除图片回调>===============
/**
 删除图片回调
 */
-(void)didDeletePhotoImage:(NSMutableArray *)imageArray
{
    _picDataArray = imageArray;
    //没有删除完毕
    if (_picDataArray.count > 0) {
        UIImage *localImage = [UIImage imageWithContentsOfFile:[_picDataArray objectAtIndex:0]];
        if (localImage) {
            [self addImageView:localImage];
        }
        else{
            NSString *url = [NSString stringWithFormat:@"%@/%@", kClientImageRootURL, [_picDataArray objectAtIndex:0]];
            UIImage *netImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
            [self addImageView:netImage];
        }
        //重置图片位置
        [self onResetImageArea];
        _valueStr = [_picDataArray yy_modelToJSONString];
        _optional = @"0";
        return;
    }
    
    //全部删除完成
    _valueStr = @"";
    [showImageView removeFromSuperview];
    showImageView  = nil;
    [self onResetImageArea];
    [SEGUtils ValueToString:[_params valueForKey:@"required"]];
}

/**
 添加图片显示view
 */
-(void)addImageView:(UIImage *)image {
    
    if(showImageView) {//已经存在图片
        [cornerLabel setText:[NSString stringWithFormat:@"%lu",(unsigned long)_picDataArray.count]];
        if (image) {
            [showImageView setImage:[SEGUtils fixOrientation:image]];
        }
    } else {//第一次添加图片
        UIImage *image1 = image;
        showImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, PICWIDTH, PICWIDTH)];
        [showImageView setImage:[SEGUtils fixOrientation:image1]];
        showImageView.layer.cornerRadius = 5;
        [showImageView.layer setMasksToBounds:YES];
        [contentView addSubview:showImageView];
        showImageView.userInteractionEnabled = YES;
        
        //触碰显示图片
        UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showPicTapAction:)];
        [showImageView addGestureRecognizer:tap];
        
        cornerImageView = [[UIImageView alloc] init];
        [cornerImageView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"img_upload_badge")]];
        [showImageView addSubview:cornerImageView];
        [cornerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.bottom.equalTo(showImageView);
            make.size.mas_equalTo(CGSizeMake(15, 15));
        }];
        
        cornerLabel = [[UILabel alloc] init];
        cornerLabel.textColor = kColor_W;
        cornerLabel.font = kFont_10;
        cornerLabel.textAlignment = NSTextAlignmentCenter;
        cornerLabel.backgroundColor = [UIColor clearColor];
        [cornerLabel setText:[NSString stringWithFormat:@"%lu",(unsigned long)_picDataArray.count]];
        [showImageView addSubview:cornerLabel];
        [cornerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.bottom.equalTo(showImageView);
            make.size.mas_equalTo(CGSizeMake(15, 15));
        }];
        
    }
    cornerLabel.hidden = _picDataArray.count > 1?NO:YES;
    cornerImageView.hidden = _picDataArray.count > 1?NO:YES;
}

- (void)showEditedImage:(UIImage *)editedImage {
    UIImage* image = editedImage;
    /**
     *  保存图片到document目录下
     */
    //    NSData* data = UIImageJPEGRepresentation([self fixOrientation:image], 0.6);
    NSData* data = [UIImage zipImageWithImage:[SEGUtils fixOrientation:image] withCompressionQuality:0.6];
    NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSDateFormatter* nsdf2 = [[NSDateFormatter alloc] init];
    [nsdf2 setDateStyle:NSDateFormatterShortStyle];
    [nsdf2 setDateFormat:@"MMddHHmmssSSSS"];
    NSString* t2 = [nsdf2 stringFromDate:[NSDate date]];
    NSString* fileName = [NSString stringWithFormat:@"%@/%@.jpg", filePath, t2];
    
    //压缩图片+加载水印
    NSData *waterImageData = [SEGUtils ScaleImageAndMakeLogo:[UIImage imageWithData:data]];
    
    if ([waterImageData writeToFile:fileName atomically:YES]) {
        if (fileName) {
            [_picDataArray addObject:fileName];
        }
    }
    _valueStr = [_picDataArray yy_modelToJSONString];
    //设置图片
    [self addImageView:[UIImage imageWithContentsOfFile:[_picDataArray objectAtIndex:0]]];
    //重置图片位置
    [self onResetImageArea];
}


/**
 *  显示点击略图查看放大图
 *
 *  @param recognizer 触碰事件
 */
- (void)showPicTapAction:(UIGestureRecognizer*)recognizer
{
    SEGShowPhotoView *browseView = [[SEGShowPhotoView alloc] initWithImageUrls:_picDataArray writable:_params[@"writable"]];
    browseView.delegate = self;
    [self.masterVC.navigationController pushViewController:browseView animated:NO];
    
}

- (void)uploadQueueResetArea:(UIImageView*)imageView
{
    int i = 0;
    for (UIImageView* aimageView in contentView.subviews) {
        if ([aimageView isKindOfClass:[UIImageView class]]) {
            if ([aimageView isEqual:imageView]) {
                [saveImageArray removeObjectAtIndex:i];
                [imageView removeFromSuperview];
            }
            i++;
        }
    }
    [self onResetImageArea];
}


- (UIView*)viewForZoomingInScrollView:(UIScrollView*)scrollView
{
    for (UIImageView* aImageView in scrollView.subviews) {
        if ([aImageView isKindOfClass:[UIImageView class]]) {
            return aImageView;
            break;
        }
    }
    return nil;
}

- (void)scrollViewDidZoom:(UIScrollView*)scrollView
{
    for (UIImageView* aImageView in scrollView.subviews) {
        if ([aImageView isKindOfClass:[UIImageView class]]) {
            //            aImageView.center = scrollView.center;
            break;
        }
    }
}

//关闭图片显示窗口
- (void)closeTapAction:(UIGestureRecognizer*)recongnizer
{
    [[recongnizer view] removeFromSuperview];
}

/**
 *  给图像框控件填充值
 *
 *  @param valueStr 接收字符串值
 */
- (void)paddingPhotoView:(id)attrValue
{
    //过滤数据
    NSMutableArray *tempValue = [[NSMutableArray alloc] init];
    if ([attrValue isKindOfClass:[NSString class]]) {
        NSString *str = (NSString *)attrValue;
        NSArray *arr = [SEGUtils arrayWithJsonString:str];
        [tempValue addObjectsFromArray:arr];
    }
    if (tempValue.count == 0) {
        return;
    }
    _picDataArray = tempValue;
    UIImage *localImage = [UIImage imageWithContentsOfFile:[_picDataArray objectAtIndex:0]];
    if (localImage) {
        [self addImageView:localImage];
    }
    else{
        NSString *url = [NSString stringWithFormat:@"%@%@", kClientImageRootURL,[_picDataArray objectAtIndex:0]];
        UIImage *netImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
        netImage = netImage?netImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_300_300")];
        [self addImageView:netImage];
    }
    
    //重置图片位置
    [self onResetImageArea];
    
    _valueStr = [_picDataArray yy_modelToJSONString];
    _optional = @"0";
}

/**
 填充默认值 - 这个默认值 在没有本地图片的情况下是显示的，一旦填充了本地数据，这个数据就没了
 */
-(void)paddingDefaultValue
{
    if (_defaultValue.length == 0) {
        return;
    }
    //1.取出默认图片数组 - 网络图片
    NSArray *picArray = [SEGUtils arrayWithJsonString:_defaultValue];
    
    if (picArray.count == 0) {
        [_picDataArray addObject:_defaultValue];
        [self addDefaultImage];
        return;
    }
    
    //将图片数据保存到数据源中
    [_picDataArray addObjectsFromArray:picArray];
    NSString *url = [NSString stringWithFormat:@"%@%@", kClientImageRootURL,[_picDataArray objectAtIndex:0]];
    UIImage *netImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
    if (netImage == nil) {
        netImage = [UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_300_300")];
    }
    [self addImageView:netImage];
    [self onResetImageArea];
    
    _valueStr = [SEGUtils ValueToString:_picDataArray];
    _optional = @"0";
}

/**
 图片路径给的格式不对我们直接取字符串试试
 */
-(void)addDefaultImage
{
    NSString *url = [NSString stringWithFormat:@"%@%@", kClientImageRootURL,_defaultValue];
    UIImage *netImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
    if (netImage == nil) {
        netImage = [UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_300_300")];
    }
    [self addImageView:netImage];
    [self onResetImageArea];
    _valueStr = [_picDataArray yy_modelToJSONString];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    // 适配开启热点页面下移的问题
    CGRect tempRect = self.view.frame;
    self.view.frame = CGRectMake(tempRect.origin.x, 0, tempRect.size.width, tempRect.size.height);
}

@end

